import os
import time
from threading import Thread, Condition
import sys
from common.utility import Utility

# 主函数
def main(is_notify_all: bool | None = False, is_wait_for: bool = False, thread_count: int = 500) -> None:
    """
    主函数。测试线程及Condition。
    Args:
        is_notify_all (bool):主线程是否使用notify_all发送通知。True-notify_all；False-notify；None-不发送通知。
        is_wait_for (bool):子线程是否使用wait_for等待通知。True-wait_for；False-wait。
        thread_count (int):子线程的数量。

    Returns:
        无。
    """
    global count
    Utility.print_info('entered.')
    threads: list[Thread] = []
    for i in range(thread_count):
        threads.append(start_thread(is_wait_for))
    time.sleep(1)
    with condition:
        if is_notify_all == True:
            condition.notify_all()
        elif is_notify_all == False:
            condition.notify()
    time.sleep(1)
    Utility.print_info(f'exited. count is {count}.')

# 创建线程
def start_thread(is_wait_for: bool) -> Thread:
    thread: Thread = Thread(target=task, args=(is_wait_for,))
    thread.start()
    return thread

# 任务
def task(is_wait_for: bool) -> None:
    global count, condition
    Utility.print_info('entered.')
    with condition:
        wait_result: bool
        if is_wait_for:
            # wiat_for-等待，直到计算条件为真时返回True，或者超时返回False。
            wait_result = condition.wait_for(lambda: os.urandom(1)[0]>128, 0.0000000001)
        else:
            # wait-等待，直到收到通知返回True，或者超时返回False。
            wait_result = condition.wait(1.05)
        if wait_result:
            count += 1
            Utility.print_info('I got notify.')
        else:
            Utility.print_info("I didn't get notify.")

print(f'is gil enabled: {sys._is_gil_enabled()}')
print(f'python version: {sys.version}')
count: int = 0
condition: Condition = Condition()
main(None, True, 5)